package com.harvest.scientific.ladder.base

import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity

open class BaActivity : AppCompatActivity(), ILoading {

    protected var isFinished = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }


    override fun showLoading() {
    }

    override fun dismissLoading() {
    }

    override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
        handleFinish()
        return super.onOptionsItemSelected(menuItem)
    }

    open fun handleFinish() {
        supportFinishAfterTransition()
    }

    override fun onPause() {
        super.onPause()
        if (!isFinished && isFinishing) {
            isFinished = true
            onRecycler()
        }
    }

    override fun onDestroy() {
        if (!isFinished) {
            isFinished = true
            onRecycler()
        }
        super.onDestroy()
    }

    open fun onRecycler() {

    }

    protected fun addFragment(fragment: BaseFragment, tag: String? = ""): BaseFragment? {
        return addFragment(fragment, false, tag)
    }

    protected fun addFragment(fragment: BaseFragment, needAddToBackStack: Boolean, tag: String? = ""): BaseFragment? {
        val fm = supportFragmentManager
        val fragmentTransaction = fm.beginTransaction()
        if(tag.isNullOrEmpty()) {
            fragmentTransaction.replace(fragment.getContainerId(), fragment)
        } else {
            fragmentTransaction.replace(fragment.getContainerId(), fragment, tag)
        }
        if (needAddToBackStack) {
            fragmentTransaction.addToBackStack(null)
        }
        try {
            fragmentTransaction.commitAllowingStateLoss()
        } catch (e: Exception) {
        }
        return fragment
    }

}